package com.fee.master.service;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import com.fee.master.MainActivity;
import com.fee.master.R;
import com.fee.master.db.ConfigCenter;
import com.fee.master.model.DayStat;
import com.fee.master.model.MonthStat;
import com.fee.master.util.Constants;
import com.fee.master.util.DateUtil;

public class SmsDetailObserver extends ContentObserver {
	
	private static final String TAG = "DetailSmsObserver";
	private static final int DETAIL_SERVICE_STATUS_ID = 115;
	
	public static boolean registed = false;
	
	//需要在安装完后进行初始化
	public static int oldCount = 0;
	
	private Context context;
	
	private static final String[] SMS_PROJECTION = {
		"address","person","date","type",
	};

	public SmsDetailObserver(Context context,Handler handler) {		
		super(handler);
		this.context = context;
	}
	
	public void onChange(boolean selfChange){
		Log.i(TAG, "on change");
		
		String orderBy = "date desc";		
		ContentResolver content = context.getContentResolver();
		Cursor cursor = content.query(Uri.parse(Constants.URI_SMS), SMS_PROJECTION, null, null, orderBy);
		int curCount = cursor.getCount();
		String smsType = "";
		
		if(cursor.moveToFirst()&& curCount>=oldCount ){
			
			String number = cursor.getString(cursor.getColumnIndex("address"));
			int type = cursor.getInt(cursor.getColumnIndex("type"));
			long smsTime = cursor.getLong(cursor.getColumnIndex("date"));
			String time = DateUtil.formatDate(smsTime, Constants.yyyyMMddHHmmss);
			
			Log.d(TAG, "number="+number+",type="+type+",time="+time);
			
			//1-接收，2-发出
			if(type==1){
				smsType = Constants.MSG_IN;
			}else if(type ==2){
				smsType = Constants.MSG_OUT;
			}
			
			String month = time.substring(0, 6);
			String day = time.substring(0,8);
			String mSelection = MonthStat.MONTH+" ='"+month+"' and "+MonthStat.KEY+"='"+smsType+"'";
			String dSelection = DayStat.DAY+" ='"+day+"' and "+DayStat.KEY+"='"+smsType+"'";
			
			//插入月统计数据
			ContentValues mValues = new ContentValues();
			mValues.put(MonthStat.MONTH, month);
			mValues.put(MonthStat.KEY, smsType);
			mValues.put(MonthStat.NUM, 1);
			Cursor c = context.getContentResolver().query(MonthStat.URI_MONTH_STAT, null, mSelection, null, null);
			
			if(c!= null && c.getCount()>0){
				context.getContentResolver().update(MonthStat.URI_MONTH_STAT, mValues, null, null);
			}else{							
				context.getContentResolver().insert(MonthStat.URI_MONTH_STAT, mValues);
			}
			c.close();
			
			//插入日统计数据
			ContentValues dValues = new ContentValues();
			dValues.put(DayStat.DAY, day);
			dValues.put(DayStat.KEY, smsType);
			dValues.put(DayStat.NUM, 1);
			
			Cursor dc = context.getContentResolver().query(DayStat.URI_DAY_STAT, null, dSelection, null, null);
			if(dc!= null && dc.getCount()>0){
				context.getContentResolver().update(DayStat.URI_DAY_STAT, dValues, null, null);
			}else{							
				context.getContentResolver().insert(DayStat.URI_DAY_STAT, dValues);
			}
			dc.close();	
			
		}
		cursor.close();
		
		//把当前短信总量记录成上一次
		oldCount= curCount;
		
		if(smsType.equals(Constants.MSG_OUT) && checkOverMaxTime()){
			showNotify();
		}
	}
	
	
	private boolean checkOverMaxTime(){
		String max = ConfigCenter.getValue(context, Constants.KEY_WARN_SMS, "0");
		if("".equals(max) || "0".equals(max)){
			return false;
		}else{
			int curNum = 0;
			String selection = MonthStat.MONTH+"="+ DateUtil.getCurrentDate("yyyyMM");
			selection = selection +" and "+MonthStat.KEY+"='"+Constants.MSG_OUT+"'";
	        Cursor c = context.getContentResolver().query(MonthStat.URI_MONTH_STAT, null, selection, null, null);
	        if(c.moveToFirst()){
	        	curNum = c.getInt(c.getColumnIndex(MonthStat.NUM));	        	
	        }
	        c.close();
	        if(curNum > Integer.valueOf(max)){
	        	return true;
	        }else{
	        	return false;
	        }
		}		
	}
	
	private void showNotify(){
		NotificationManager nfManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification nf = new Notification();
		nf.icon = R.drawable.icon;
		nf.tickerText = context.getResources().getString(R.string.notify_desc_sms);
		PendingIntent contentIntent = PendingIntent
				.getActivity(context, 0, new Intent(context,MainActivity.class), 0);
		
		String max = ConfigCenter.getValue(context, Constants.KEY_WARN_SMS, "0");
		String title = context.getResources().getString(R.string.app_name);
		String desc = context.getResources().getString(R.string.notify_desc_sms)+":"+max+context.getResources().getString(R.string.sms_count);
		nf.setLatestEventInfo(context, title,desc, contentIntent);
		nf.flags = Notification.FLAG_NO_CLEAR;

		nfManager.notify(DETAIL_SERVICE_STATUS_ID, nf);
	}

}
